package com.banksoft.front.controller;


import com.banksoft.admin.SystemCache;
import com.banksoft.admin.bean.Enable;
import com.banksoft.admin.bean.LoginType;
import com.banksoft.admin.bean.MemberType;
import com.banksoft.admin.bean.Status;
import com.banksoft.admin.dao.UserDao;
import com.banksoft.admin.entity.Notice;
import com.banksoft.admin.entity.User;
import com.banksoft.admin.service.BaseService;
import com.banksoft.admin.service.NoticeService;
import com.banksoft.admin.service.UserService;
import com.banksoft.admin.service.WxReceiveMessageService;
import com.banksoft.common.BaseController;
import com.banksoft.common.ConfigHelper;
import com.banksoft.front.util.WeixinUtil;
import com.banksoft.util.MD5Util;
import com.banksoft.util.StringUtil;
import com.banksoft.util.UUIDFactory;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/3/31.
 */
@Controller
public class FrontIndexController extends BaseController {

    private static Logger logger  = LoggerFactory.getLogger(FrontIndexController.class);

    @Autowired
    UserService userService;
    @Autowired
    BaseService baseService;
    @Autowired
    NoticeService noticeService;
    @Autowired
    WxReceiveMessageService wxReceiveMessageService;

    @RequestMapping("/wx/index")
    public String index(String state, Model model){
       model.addAttribute("recommendId",state);
        return "front/index";
        // return "front/login";
    }
    @RequestMapping("/wx/login")
    @ResponseBody
    public JSONObject login(String account,HttpServletRequest request){
        try{
          List<User>  list =  userService.findByAccount(account);
            if(StringUtil.isNotEmpty(list)){
                User user = list.get(0);
                autoSession(user);
                request.getSession().setAttribute(SystemCache.SESSION_USER,list.get(0));
                return this.FmtResult(true,"登录成功",null);
            }
            return this.FmtResult(false,"没有找到对应的账号",null);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,"登录失败",null);
    }

    /**
     * 自动登录
     * @param user
     */
    private void autoSession(User user){
        Subject subject = SecurityUtils.getSubject();
        String key = user.getId() + "|"+ LoginType.Member.name();
        UsernamePasswordToken token = new UsernamePasswordToken(key, user.getPassword());
        token.setRememberMe(true);
        subject.login(token);
    }

    /**
     * 用户进入时获取用户信息
     *
     * @return
     */
    @RequestMapping("/wx/getAuth")
    @ResponseBody
    public JSONObject getAuth(String recommendId,HttpServletRequest request)  {
        String backUrl = "http://boaishangcheng.com/wx/getUserInfo";
                //getDomain(request)+"/wx/getUserInfo";
        String redirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ SystemCache.AppId
                +"&redirect_uri=" + backUrl + "&response_type=code&scope=snsapi_userinfo"+
                "&state="+recommendId+"#wechat_redirect";
        return this.FmtResult(true,null,redirectUrl);
    }

    @RequestMapping("/wx/getUserInfo")
    public String getUserInfo(String code, String state, HttpServletRequest request, HttpServletResponse response) {
        logger.info("----------  "+code);
        String openId = null;
        if(!StringUtil.isNullOrEmpty(code)) {
            Map map = WeixinUtil.getOpenId(code);
            if (map != null) {
                openId = (String) map.get("openid");
                //查看openid是否存在  不存在查询
                User dto = this.userService.findByOpenId(openId);
                if(dto==null){
                    String access_token = (String) map.get("access_token");
                    if (!StringUtil.isNullOrEmpty(openId)) {
                        Map data = WeixinUtil.getUserInfo(access_token, openId);
                        if (data != null) {
                            if (data.get("errorcode") == null) {
                                String userOpenId = (String) data.get("openid");
                                String nickname = (String) data.get("nickname");
                                String sex = data.get("sex") + "";
                                String country = (String) data.get("country");
                                String province = (String) data.get("province");
                                String city = (String) data.get("city");
                                String headimgurl = (String) data.get("headimgurl");

                                dto = new User();
                                dto.setId(UUIDFactory.random());
                                dto.setCity(city);
                                dto.setPassword(MD5Util.getMD5ofStr(ConfigHelper.GetInstance().GetConfig("Init_Pwd")));
                                dto.setAccount(getMemberAccount());
                                dto.setOpenId(userOpenId);
                                dto.setNickName(nickname);
                                dto.setIsShare(Enable.No.name());
                                dto.setSex(sex);
                                dto.setCountry(country);
                                dto.setProvince(province);
                                dto.setHeadimgUrl(headimgurl);
                                dto.setIsMember("0");//非正式会员
                                dto.setRecommendId(state);
                                dto.setType(MemberType.Customer.name());
                                dto.setStatus(Status.NORMAL.name());
                                dto.setCreateTime(new Date().getTime());
                                dto.setLastLoginTime(new Date().getTime());
                                try {
                                    this.userService.saveUser(dto);
                                }catch (Exception e){//此处有可能你成保存时出现错误
                                    dto.setNickName("");//出现错误时 不保存昵称
                                    this.userService.saveUser(dto);
                                }
                            }
                        }
                      }
                }else{//用户存在时 判断当前用户是否是正式会员  如果不是 则更新会员推荐人
                    if(!"1".equals(dto.getIsMember())){//不是正式会员
                        if(StringUtil.isNotNull(state)){
                            if(!dto.getId().equals(state)){//不是通过扫描本人的id进入的
                                if(dto.getLastLoginTime()!=null){//如果记录了上次登录进入时间
                                    long now = new Date().getTime();
                                    if(((now - dto.getLastLoginTime())/(24*60*60*1000))>2){//超过3天
                                        dto.setRecommendId(state);
                                        dto.setLastLoginTime(new Date().getTime());
                                    }else{
                                        if(!StringUtil.isNotNull(dto.getRecommendId())) {
                                            dto.setRecommendId(state);
                                            dto.setLastLoginTime(new Date().getTime());
                                        }
                                    }
                                }else{//没有记录上次登录时间的话 更新推荐人
                                    dto.setRecommendId(state);
                                    dto.setLastLoginTime(new Date().getTime());
                                }
                            }
                        }
                        dto.setIsMember("0");
                        this.baseService.update(UserDao.class,dto);
                    }
                }
                autoSession(dto);
                request.getSession().setAttribute(SystemCache.SESSION_USER,dto);
            }
        }
        return "redirect:/front/productList";
    }

    private String getMemberAccount(){
        String account = StringUtil.getRandom(8);
        List<User> list = this.userService.findByAccount(account);
        if(StringUtil.isNotEmpty(list)){
            return getMemberAccount();
        }else{
            return account;
        }
    }

    @RequestMapping("/wx/share")
    public String share(){
        return "/front/share";
    }


    @RequestMapping("/wx/receive")
    @ResponseBody
    public  void receive(HttpServletRequest request,HttpServletResponse response){
        try {
            this.wxReceiveMessageService.receive(request,response,"123321");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/wx/getUpdateConfig")
    @ResponseBody
    public JSONObject getUpdateConfig(int type){
        try{
            ConfigHelper instance = ConfigHelper.GetInstance();
            String msg = "";
            if(type==2){
                msg = instance.GetConfig("Partner_Fee");
            }else if(type==1){
                msg = instance.GetConfig("General_Fee");
            }else{
                msg = instance.GetConfig("Gold_Fee");
            }
            return this.FmtResult(true,null,msg);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,"读取配置失败",null);
    }


    /**
     * 从模板消息处  自动登录
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/wx/autoLogin")
    public String autoLogin(String id,HttpServletRequest request){
        if(StringUtil.isNotNull(id)){
            User user = this.baseService.findById(UserDao.class,id);
            if(user!=null){
                autoSession(user);
                request.getSession().setAttribute(SystemCache.SESSION_USER,user);
                return "redirect:/front/user/main";
            }
        }
        return "redirect:/wx/index";
    }

    @RequestMapping("/front/loadNotice")
    @ResponseBody
    public JSONObject loadNotice(){
        try{
            //只取最近的一条数据
            List<Notice> list = this.noticeService.loadNotices(1);
            if(StringUtil.isNotEmpty(list)){
                return this.FmtResult(true,null,list.get(0));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,null,null);
    }

}
